package com.ruoyi.common.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

public class detectUtils {
    //检测
    public static String detect(String s) {
        System.out.println("--------------------------算法检测开始---------------------------");
        System.out.println(s);
        StringBuilder stringBuilder = new StringBuilder();
        try {
            Process proc = Runtime.getRuntime().exec(s);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                stringBuilder.append(line);
            }
            in.close();
            proc.waitFor();
            System.out.println("--------------------------算法检测结束---------------------------");
        } catch (IOException e ) {
            e.printStackTrace();
        } catch ( InterruptedException e){
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    //File转MultipartFile
    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }
}
